package com.firmail.aspect;

import com.firmail.mock.util.GsonUtils;
import com.firmail.response.ResponseInfo;
import com.firmail.thread.MockThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;


/**
 * @author dzs
 * @date 2018年1月12日 上午10:24:24
 */
//@Aspect
//@Component
@Slf4j
public class ReturnAspect {

    /**
     * TODO 时间的统计aop 过滤器
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Around("execution(* com.firmail.controller.*.*(..))")
    public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        ResponseInfo<Object> info = new ResponseInfo<>();
        long start = System.nanoTime();
        annotation(joinPoint);
        Object proceed = joinPoint.proceed();
        info.setData(proceed);
        try {
            MockThreadLocal.getResponse().getWriter().println(GsonUtils.toJson(info));
        } finally {
            MockThreadLocal.clear();
        }

        log.info("请求处理结束：【method】 : {}, [总共耗时]： {}",
                joinPoint.getTarget() + "." + joinPoint.getSignature().getName() ,
                String.format("%d ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-start)) );


    }

    private void annotation(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Annotation[] annotations = signature.getMethod().getAnnotations();
        if (annotations != null) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof RequestMapping) {
                    String[] value = ((RequestMapping) annotation).value();
                    log.debug("RequestMapping->" + Arrays.toString(value));
                    //break;
                }
            }
        }
    }
}
